package com.codemobiles.droidslator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.codemobiles.droidslator.activity.ContactUsActivity;
import com.codemobiles.droidslator.activity.ListFlagActivity;
import com.codemobiles.droidslator.activity.SettingActivity;
import com.codemobiles.droidslator.dicts.DictSpec;
import com.codemobiles.droidslator.dicts.DictionaryFactory;
import com.codemobiles.droidslator.manager.LanguageMgr;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

//import com.google.tts.TTS;

/**
 * 
 * @author Administrator
 */
public class Droidslator extends Activity {
	private ImageView translateBtn;
	private ImageView eraserBtn;
	private ImageView imgContactus;
	private EditText fromEditor;
	private ScrollView layEditor;
	private EditText toEditor;
	private LanguageMgr langMgr;
	private FrameLayout fraFlag;
	private AlertDialog dlgListViewIcon;
	private AlertDialog dlgAlert;
	private SimpleImage imgFocus;
	private SelectionView selectView;
	private TextView txvTitle;

	private String strError;

	private DisplayMetrics displayMetrics;
	private int startTouchX = 0;
	private boolean released = false;
	private boolean hold = false;

	private static final int DIALOG_ALERT = 2;
	private static final int DIALOG_LIST_CONFIG = 3;

	private static final int LIST_FLAG_ACTIVITY_ID = 0x001;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title);

		// get screen width and height
		displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		langMgr = new LanguageMgr(this);

		translateBtn = (ImageView) findViewById(R.id.imgTranslate);
		eraserBtn = (ImageView) findViewById(R.id.imgEraser);
		fromEditor = (EditText) findViewById(R.id.fromEditor);
		layEditor = (ScrollView) findViewById(R.id.layEditor);
		toEditor = (EditText) findViewById(R.id.toEditor);
		imgContactus = (ImageView) findViewById(R.id.imgContactus);
		fraFlag = (FrameLayout) findViewById(R.id.fraFlag);
		txvTitle = (TextView) findViewById(R.id.txvTitle);

		setInitFromEditText();
		setInitToEditText();
		setInitEraserButton();
		setInitTranslateButton();
		setInitContactUsButton();

		// Draw flag and add to FrameLayout
		selectView = new SelectionView(this);
		fraFlag.addView(selectView);

		// Set translation title
		setTranslateTitle();

	}

	private void setInitContactUsButton() {
		imgContactus.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int eventaction = event.getAction();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN:
					imgContactus
							.setImageResource(R.drawable.button_contact_touch);
					break;

				case MotionEvent.ACTION_MOVE:
					break;

				case MotionEvent.ACTION_UP:
					imgContactus.setImageResource(R.drawable.button_contact);
					break;
				}

				return false;
			}
		});
		imgContactus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hideKeyboard(fromEditor.getWindowToken());
				Intent iContactUs = new Intent(Droidslator.this,
						ContactUsActivity.class);
				startActivity(iContactUs);
			}
		});
	}

	private void setInitTranslateButton() {
		translateBtn.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int eventaction = event.getAction();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN:
					translateBtn
							.setImageResource(R.drawable.button_translate_touch);
					break;

				case MotionEvent.ACTION_MOVE:
					break;

				case MotionEvent.ACTION_UP:
					translateBtn.setImageResource(R.drawable.button_translate);
					break;
				}

				return false;
			}
		});
		translateBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hideKeyboard(fromEditor.getWindowToken());
				if (fromEditor.length() != 0) {
					translateIt();
				}
			}
		});
	}

	private void setInitEraserButton() {
		eraserBtn.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int eventaction = event.getAction();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN:
					eraserBtn.setImageResource(R.drawable.button_config_touch);
					break;

				case MotionEvent.ACTION_MOVE:
					break;

				case MotionEvent.ACTION_UP:
					eraserBtn.setImageResource(R.drawable.button_config);
					break;
				}

				return false;
			}
		});
		eraserBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// call setting activity
				hideKeyboard(fromEditor.getWindowToken());
				Intent iSetting = new Intent(Droidslator.this,
						SettingActivity.class);
				startActivity(iSetting);
			}
		});
	}

	private void clearInput() {
		fromEditor.setText("");
		toEditor.setText("");
	}

	private void setInitFromEditText() {
		fromEditor.setOnKeyListener(new View.OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					translateIt();
					hideKeyboard(fromEditor.getWindowToken());
					return true;
				}
				return false;
			}
		});
		fromEditor.setText(getString(R.string.from_translate_title));
		fromEditor.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					Log.i("POS_TAG", "fixed text = "
							+ getString(R.string.from_translate_title));
					Log.i("POS_TAG", "fromEditor = " + fromEditor.getText());
					Log.i("POS_TAG", "equal = "
							+ fromEditor.getText().equals(
									getString(R.string.from_translate_title)));
					if (fromEditor.getText().toString().equals(
							getString(R.string.from_translate_title))) {
						fromEditor.setText("");
					}
				} else {
					if (fromEditor.getText().length() == 0) {
						fromEditor
								.setText(getString(R.string.from_translate_title));
					}
					hideKeyboard(fromEditor.getWindowToken());
				}

			}
		});
		fromEditor.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int eventaction = event.getAction();
				int X = (int) event.getX();
				int Y = (int) event.getY();

				switch (eventaction) {

				case MotionEvent.ACTION_DOWN:
					hold = true;
					startTouchX = X;
					Log.i("POS_TAG", fromEditor.getLeft() + ", "
							+ fromEditor.getRight() + "");
					break;

				case MotionEvent.ACTION_MOVE:
					break;

				case MotionEvent.ACTION_UP:
					int borderTopBottom = 8;
					int startX = fromEditor.getLeft();
					int endX = fromEditor.getRight();
					int startY = fromEditor.getTop() - borderTopBottom;
					int endY = fromEditor.getBottom() + borderTopBottom;
					int widthDetectAction = displayMetrics.widthPixels / 6; // 16.67%
					// if touch position start don't in this object not take
					// action
					if (startTouchX < startX && startTouchX > endX) {
						break;
					}

					// if touch position released in this object take clear
					// input
					/*if (X >= startX && X <= endX && Y >= startY && Y <= endY) {
						// of
						// current
						// width
						// screen
						if (X - startTouchX > widthDetectAction) {
							clearInput();
							if (hold)
								return true;
						}
					}*/
					Log.i("POS_TAG", "widthScreen="
							+ displayMetrics.widthPixels
							+ " : widthDetectAction=" + widthDetectAction);
					Log.i("POS_TAG", "fromEditor," + released + ", " + startX
							+ ", " + endX + ", " + startY + ", " + endY);
					Log.i("POS_TAG", X + ", " + Y);

					startX = layEditor.getLeft();
					endX = layEditor.getRight();
					startY = layEditor.getTop();
					endY = layEditor.getBottom();
					// if touch position released out of this object not take
					// action
					if (X >= startX && X <= endX && Y >= startY && Y <= endY) {
						translateIt();
					} else {
						clearInput();
						//if (hold) return true;
					}
					Log.i("POS_TAG", "toEditor," + released + ", " + startX
							+ ", " + endX + ", " + startY + ", " + endY);
					Log.i("POS_TAG", X + ", " + Y);
					hold = false;
				}

				return false;
			}
		});
	}

	private void setInitToEditText() {
		toEditor.setMovementMethod(new ScrollingMovementMethod());
	}

	private void hideKeyboard(IBinder curWindowToken) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(curWindowToken, 0);
	}

	/*
	 * // Set initiate TTS private TTS.InitListener ttsInitListener = new
	 * TTS.InitListener() { public void onInit(int version) { } };
	 */

	private void translateIt() {
		String fromLangCode = selectView.getFromFlagCode();
		String toLangCode = selectView.getToFlagCode();
		String fromLangName = langMgr.getLangNameByCode(fromLangCode);
		String toLangName = langMgr.getLangNameByCode(toLangCode);
		final String inputWord = fromEditor.getText().toString().trim();
		final String GOOGLE_TRANSLATOR_URL = "http://code.google.com/p/google-api-translate-java/";
		StringBuffer res = new StringBuffer();
		// Set the HTTP referrer to your web site address.
		Translate.setHttpReferrer(GOOGLE_TRANSLATOR_URL);
		try {

			DictSpec dict = DictionaryFactory.getDictionary(fromLangName);
			if (dict != null) {
				res.append(dict.translate(inputWord, toLangName));
				if (res.toString().equals("") != true) {
					res.insert(0, "From: (Offline Dictionary)\n\n");
				}
				toEditor.setText(res);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (res.toString().equals("")) {

			Log.i("From Lang: To Lang", fromLangName + ":" + toLangName);
			try {
				ConnectivityManager internetConn = (ConnectivityManager) this
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				if (internetConn.getActiveNetworkInfo().isConnected() == true) {
					res.append(Translate.translate(fromEditor.getText()
							.toString(), Language.valueOf(fromLangName),
							Language.valueOf(toLangName)));
					if (res.toString().equals("") != true) {
						res.insert(0, "From: (Online Dictionary)\n\n");
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (res.toString().equalsIgnoreCase("")) {
			res.append("Not found");
		}
		toEditor.setText(res.toString());

	}

	public void swapText() {
		String tmp = fromEditor.getText().toString();
		fromEditor.setText(toEditor.getText());
		toEditor.setText(tmp);
	}

	public void showListConfig() {
		if (dlgListViewIcon == null) {
			showDialog(DIALOG_LIST_CONFIG);
		} else {
			dlgListViewIcon.show();
		}
	}

	public void showList(SimpleImage img, String lastRegStr) {
		imgFocus = img;
		Intent intent = new Intent(this.getApplicationContext(),
				ListFlagActivity.class);
		intent.putExtra("lastReg", lastRegStr);
		startActivityForResult(intent, LIST_FLAG_ACTIVITY_ID);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (data != null) {
			switch (requestCode) {
			case (LIST_FLAG_ACTIVITY_ID): {
				String flagCode = data.getExtras().get("FLAG_CODE").toString();
				;
				if (flagCode != null) {
					if (selectView.setBitmapFile(flagCode, imgFocus)) {
						setTranslateTitle();
					} else {
						showAlert(getString(R.string.alert_flag_duplicate));
					}
				}
				break;
			}
			}
		}
	}

	public void showAlert(String text) {
		if (dlgAlert == null) {
			showDialog(DIALOG_ALERT);
		} else {
			dlgAlert.setMessage(text);
			dlgAlert.show();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ALERT:
			dlgAlert = new AlertDialog.Builder(Droidslator.this).setMessage(
					strError).create();
			return dlgAlert;

		}

		return null;
	}

	public void setTranslateTitle() {
		String FromFlagName = langMgr.convertNameToShort(langMgr
				.getLangNameByCode(selectView.getFromFlagCode()));
		String ToFlagName = langMgr.convertNameToShort(langMgr
				.getLangNameByCode(selectView.getToFlagCode()));

		Log.i("POS_TAG", FromFlagName + " - " + ToFlagName);
		txvTitle.setText(FromFlagName + " - " + ToFlagName);
	}
}